package com.sunday.fangdaifu.activity.task;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.android.flexbox.FlexboxLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.squareup.picasso.Picasso;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.imageselector.MultiImageSelectorActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.ImageUtils;
import com.sunday.common.utils.PixUtils;
import com.sunday.common.utils.StringUtils;
import com.sunday.common.utils.TimeCount;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.gridview.NoScrollGridView;
import com.sunday.fangdaifu.R;
import com.sunday.fangdaifu.adapter.CommenAdapter;
import com.sunday.fangdaifu.adapter.ViewHolder;
import com.sunday.fangdaifu.common.Api;
import com.sunday.fangdaifu.common.ApiClient;
import com.sunday.fangdaifu.common.ApiServiceImpl;
import com.sunday.fangdaifu.common.AppConfig;
import com.sunday.fangdaifu.model.HousePart;
import com.sunday.fangdaifu.model.TaskDetail;
import com.sunday.fangdaifu.model.UploadImg;
import com.sunday.fangdaifu.utils.DateUtil;
import com.sunday.fangdaifu.utils.SharePerferenceUtils;
import com.sunday.fangdaifu.utils.VoiceManager;
import com.sunday.fangdaifu.widgets.RecordTimer;
import com.sunday.fangdaifu.widgets.SelectDirectionWindow;
import com.sunday.fangdaifu.widgets.VoiceLineView;

import java.io.File;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.Manifest.permission.RECORD_AUDIO;
import static android.Manifest.permission.VIBRATE;
import static com.sunday.fangdaifu.common.Const.TASK_ID;


/**
 * Created by yun_sheng on 2017/7/3.
 */

public class CommitTaskActivity extends BaseActivity implements ApiServiceImpl.HttpResponseInterface {


    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.ly_room_type)
    RelativeLayout lyRoomType;
    @Bind(R.id.ly_structure)
    RelativeLayout lyStructure;
    @Bind(R.id.view1)
    View view1;
    @Bind(R.id.ly_room_use)
    RelativeLayout lyRoomUse;
    @Bind(R.id.ly_add_item)
    LinearLayout lyAddItem;
    @Bind(R.id.btn_more_problem)
    LinearLayout btnMoreProblem;
    @Bind(R.id.scrollView)
    ScrollView scrollView;
    @Bind(R.id.bottom)
    LinearLayout bottom;
    @Bind(R.id.house_type)
    TextView houseType;
    @Bind(R.id.building_type)
    TextView buildingType;
    @Bind(R.id.house_usage)
    TextView houseUsage;
    @Bind(R.id.layout_recorder)
    FrameLayout layoutRecorder;
    @Bind(R.id.voice_view)
    VoiceLineView voiceLineView;
    @Bind(R.id.timer)
    TextView timer;
    @Bind(R.id.btn_stop)
    TextView btnStop;
    @Bind(R.id.layout_play_recorder)
    RelativeLayout layoutPlayRecorder;
    @Bind(R.id.btn_play_stop)
    TextView btnPlayStop;
    @Bind(R.id.btn_start_play)
    ImageView btnStartPlay;
    @Bind(R.id.progress_bar)
    ProgressBar progressBar;
    @Bind(R.id.timer_start)
    TextView timeStart;
    @Bind(R.id.timer_end)
    TextView timeEnd;


    private TaskDetail taskDetail;
    private List<View> viewList = new ArrayList<>();
    private List<ViewsHolder> lsvh = new ArrayList<>();
    private List<ImgHolder> imgHolderList = new ArrayList<>();
    RecordTimer recordTimer;
    TimeCount timerEnd;
    RecordTimer timerStart;
    String mFilename;
    private String savedJson;
    private LayoutInflater layoutInflater;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_problem_commit);
        ButterKnife.bind(this);
        title.setText("提交报告");
        layoutInflater = LayoutInflater.from(mContext);
        taskDetail = (TaskDetail) getIntent().getSerializableExtra("taskDetail");
        houseType.setText(taskDetail.getHouseType());
        buildingType.setText(taskDetail.getFrameworkType());
        houseUsage.setText(taskDetail.getNowUsage());
        mFilename = AppConfig.DEFAULT_REPORT_SAVE_FILE_PATH + String.valueOf(taskDetail.getDetailId()) + File.pathSeparator + "json.txt";
        //根据detailId先查找是否存在草稿文件
        savedJson = SharePerferenceUtils.getIns().getString(TASK_ID + taskDetail.getDetailId(), "");
        getPartsList();

        /*File file=new File(mFilename);
        if(!file.exists()){//判断文件是否存在，如果不存在则是新的
            getPartsList();
        }else {
            //读取草稿，恢复页面
        }*/

        VoiceManager.getInstance(mContext).setVoiceRecordListener(new VoiceManager.VoiceRecordCallBack() {
            @Override
            public void recDoing(long time, String strTime) {

            }

            @Override
            public void recVoiceGrade(int grade) {

            }

            @Override
            public void recStart(boolean init) {

            }

            @Override
            public void recPause(String str) {

            }

            @Override
            public void recFinish(long length, String strLength, String path) {
                //vh保存
                lsvh.get(p).videoTime = length;
                lsvh.get(p).videoPath = path;
                View view = null;
                if (!lsvh.get(p).isHaveRecordView) {
                    view = LayoutInflater.from(mContext).inflate(R.layout.layout_record_item, null);
                    lsvh.get(p).flexBoxLayout.addView(view);
                } else {
                    int count = lsvh.get(p).flexBoxLayout.getChildCount();
                    view = lsvh.get(p).flexBoxLayout.getChildAt(count - 1);
                }
                lsvh.get(p).isHaveRecordView = true;
                ViewGroup.LayoutParams params = view.getLayoutParams();
                if (params instanceof FlexboxLayout.LayoutParams) {
                    FlexboxLayout.LayoutParams layoutParams = (FlexboxLayout.LayoutParams) params;
                    layoutParams.width = PixUtils.dip2px(mContext, 90);
                    layoutParams.setFlexGrow(0);
                    layoutParams.setMaxWidth(PixUtils.dip2px(mContext, 90));
                    view.setLayoutParams(layoutParams);
                }
                TextView recordTime = (TextView) view.findViewById(R.id.record_time);
                recordTime.setText(new StringBuilder().append(lsvh.get(p).videoTime).append("\"").toString());
                ImageView imgView1 = (ImageView) view.findViewById(R.id.delete_record);
                LinearLayout llPlay = (LinearLayout) view.findViewById(R.id.layout_play_record);
                llPlay.setTag(p);
                imgView1.setTag(p);
                llPlay.setOnClickListener(onClickListener);
                imgView1.setOnClickListener(onClickListener);
            }
        });
        VoiceManager.getInstance(mContext).setVoicePlayListener(new VoiceManager.VoicePlayCallBack() {
            long total;

            @Override
            public void voiceTotalLength(long time, String strTime) {
                total = time;
            }

            @Override
            public void playDoing(long time, String strTime) {
                progressBar.setProgress((int) (time / total));
            }

            @Override
            public void playPause() {

            }

            @Override
            public void playStart() {

            }

            @Override
            public void playFinish() {
                btnStartPlay.setImageResource(R.mipmap.report_voice_play);
                if (timerStart != null)
                    timerStart.cancel();
            }
        });

    }


    private void restoreViews(List<SaveReport> datas) {
        //先添加子view
        lyAddItem.removeAllViews();
        for (int i = 0; i < datas.size(); i++) {
            initView();
            mark++;
            sortView();
        }

        Log.i("------CurrentTime", String.valueOf(System.currentTimeMillis()));
        //恢复数据
        for (int i = 0; i < datas.size(); i++) {
            ViewsHolder vh = lsvh.get(i);
            SaveReport sr = datas.get(i);
            vh.floor = sr.floor;
            vh.editFloor.setText(sr.floor);
            vh.textProblem.setText(sr.problemInfo);
            vh.selectDirection.setText(sr.position);
            vh.problemOther = sr.position;
            vh.problemType = sr.problemType;
            vh.problemName = sr.problemName;
            vh.problemInfo = sr.problemInfo;
            vh.problemOther = sr.problemOther;
            vh.videoPath = sr.video;
            vh.videoTime = sr.videoTime;
            vh.selectImgList = (ArrayList<String>) sr.images;
            for (int j = 0; j < vh.housePartList.size(); j++) {
                if (vh.housePartList.get(j).getText().equals(sr.problemName)) {
                    vh.housePartList.get(j).setSelected(true);
                    break;
                }
            }
            for (int k = 0; k < vh.selectImgList.size(); k++) {
                imgMark = k;
                View view = layoutInflater.inflate(R.layout.grid_img_layout, null);
                vh.flexBoxLayout.addView(view);
                view.setId(imgMark);
                getImgViewInstance(view, i);

            }
            if (!TextUtils.isEmpty(vh.videoPath)) {
                View view = layoutInflater.inflate(R.layout.layout_record_item, null);
                TextView recordTime = (TextView) view.findViewById(R.id.record_time);
                recordTime.setText(new StringBuilder().append(vh.videoTime).append("\"").toString());
                vh.flexBoxLayout.addView(view);
                vh.isHaveRecordView = true;
                ViewGroup.LayoutParams params = view.getLayoutParams();
                if (params instanceof FlexboxLayout.LayoutParams) {
                    FlexboxLayout.LayoutParams layoutParams = (FlexboxLayout.LayoutParams) params;
                    layoutParams.setFlexGrow(0);
                    layoutParams.width = PixUtils.dip2px(mContext, 90);
                    layoutParams.setMaxWidth(PixUtils.dip2px(mContext, 90));
                    view.setLayoutParams(layoutParams);
                }
                ImageView imgView1 = (ImageView) view.findViewById(R.id.delete_record);
                LinearLayout llPlay = (LinearLayout) view.findViewById(R.id.layout_play_record);
                imgView1.setTag(i);
                llPlay.setTag(i);
                llPlay.setOnClickListener(onClickListener);
                imgView1.setOnClickListener(onClickListener);
            }
        }
        Log.i("------CurrentTime", String.valueOf(System.currentTimeMillis()));


    }

    private int p;//记录录音的位置
    private List<String> imgPaths = new ArrayList<>();

    @OnClick({R.id.btn_more_problem, R.id.btn_stop, R.id.btn_no_problem, R.id.btn_save_draft, R.id.btn_submit, R.id.btn_start_play,
            R.id.btn_play_stop})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_more_problem:
                mark++;
                initView();
                sortView();
                break;
            case R.id.btn_stop:
                //final ViewsHolder viewsHolder = () btnStop.getTag();
                p = (int) btnStop.getTag();
                layoutRecorder.setVisibility(View.GONE);
                VoiceManager.getInstance(mContext).stopVoiceRecord();
                recordTimer.cancel();
                break;
            case R.id.btn_no_problem:
                ApiClient.getApiService().changeTaskStatus(taskDetail.getDetailId(), 2, null, null, this, new TypeToken<ResultDO>() {
                }.getType());
                break;
            case R.id.btn_save_draft:
                //本地存储
                getSaveJson();
                break;
            case R.id.btn_submit:
                imgPaths.clear();
                for (int i = 0; i < lsvh.size(); i++) {
                    lsvh.get(i).filePaths.clear();
                    String floor = lsvh.get(i).editFloor.getText().toString().trim();
                    if (TextUtils.isEmpty(floor)) {
                        ToastUtils.showToast(mContext, "请填写具体楼层");
                        return;
                    }
                    lsvh.get(i).floor = floor;
                    String direction = lsvh.get(i).selectDirection.getText().toString();
                    if (TextUtils.isEmpty(direction)) {
                        ToastUtils.showToast(mContext, "请选择方位");
                        return;
                    }
                    lsvh.get(i).position = direction;
                    if (lsvh.get(i).housePart == null) {
                        ToastUtils.showToast(mContext, "请选择具体部件");
                        return;
                    }
                    String elsePart = lsvh.get(i).editPart.getText().toString().trim();
                    if (lsvh.get(i).housePart.getId() == 0) {
                        if (TextUtils.isEmpty(elsePart)) {
                            ToastUtils.showToast(mContext, "请输入其他部件");
                            return;
                        }
                    }
                    String extraProblem = lsvh.get(i).textProblem.getText().toString().trim();
                    if (lsvh.get(i).housePart.getId() == 0 && TextUtils.isEmpty(extraProblem)) {
                        ToastUtils.showToast(mContext, "请填写具体问题");
                        return;
                    }

                    if (lsvh.get(i).selectImgList != null && !lsvh.get(i).selectImgList.isEmpty()) {
                        for (String path : lsvh.get(i).selectImgList) {
                            String pathName=ImageUtils.getCompressImagePath(path);
                            imgPaths.add(pathName);
                            lsvh.get(i).filePaths.put(pathName.substring(pathName.lastIndexOf('/') + 1, pathName.length()),pathName);
                        }
                    }
                    if (!TextUtils.isEmpty(lsvh.get(i).videoPath)) {
                        imgPaths.add(lsvh.get(i).videoPath);
                        lsvh.get(i).filePaths.put(lsvh.get(i).videoPath.substring(lsvh.get(i).videoPath.lastIndexOf('/') + 1, lsvh.get(i).videoPath.length()), lsvh.get(i).videoPath);
                    }
                    lsvh.get(i).problemOther = (lsvh.get(i).editProblem).getText().toString().trim();

                }
                //先上传图片和录音文件
                showLoadingDialog();
                if (imgPaths != null && imgPaths.size() > 0){
                    ApiClient.getApiService().uploadMulti(imgPaths, this, new TypeToken<ResultDO<List<UploadImg>>>() {
                    }.getType());
                }else {
                    getUploadJson();
                    submitReport();
                }
                break;
            case R.id.btn_start_play:
                if (VoiceManager.getInstance(mContext).isPlaying()) {
                    return;
                } else {
                    int p2 = (int) v.getTag();//外层lsvh 的位置
                    //播放录音文件
                    ViewsHolder vh = lsvh.get(p2);
                    try {
                        VoiceManager.getInstance(mContext).startPlay(vh.videoPath);
                    } catch (Exception e) {
                        return;
                    }
                    timerStart = new RecordTimer(999999999, 1000, timeStart);
                    timerStart.start();
                    btnStartPlay.setImageResource(R.mipmap.report_voice_stop);
                }
                break;
            case R.id.btn_play_stop:
                layoutPlayRecorder.setVisibility(View.GONE);
                layoutRecorder.setVisibility(View.GONE);
                break;

        }
    }


    private void getSaveJson() {
        showLoadingDialog();
        List<SaveReport> datas = new ArrayList<>();
        for (int i = 0; i < lsvh.size(); i++) {
            ViewsHolder vh = lsvh.get(i);
            String floor = vh.editFloor.getText().toString().trim();
            vh.floor = floor;
            SaveReport dat = new SaveReport(vh.floor, vh.position, vh.problemType, vh.problemName, vh.problemInfo,
                    vh.problemOther, vh.videoPath, vh.videoTime, vh.selectImgList);
            datas.add(dat);
        }
        Gson gson = new Gson();
        String saveJson = gson.toJson(datas);
        SharePerferenceUtils.getIns().putString(TASK_ID + taskDetail.getDetailId(), saveJson);
        dissMissDialog();
        ToastUtils.showToast(mContext, "保存成功");

    }


    private int mark = 0;
    private int imgMark = 0;

    private void initView() {
        View view = layoutInflater.inflate(R.layout.item_problem_commit, null);
        lyAddItem.addView(view, 0);//总是排在第一个 注意删除的时候
        view.setId(mark);
        getViewInstance(view);
    }

    private void getViewInstance(View childView) {
        final ViewsHolder vh = new ViewsHolder();
        vh.id = childView.getId();//标识viewholder 存储唯一的childview 信息
        vh.hederLayout = (RelativeLayout) childView.findViewById(R.id.header_layout);
        vh.problemIndex = (TextView) childView.findViewById(R.id.problem_index);
        vh.deleteProblem = (ImageView) childView.findViewById(R.id.delete_problem);
        vh.editFloor = (EditText) childView.findViewById(R.id.edt_problem_floor);
        vh.selectDirection = (TextView) childView.findViewById(R.id.select_direction);
        vh.partsListView = (NoScrollGridView) childView.findViewById(R.id.grid_view);
        vh.editPart = (EditText) childView.findViewById(R.id.edit_part);
        vh.lySelectProblem = (RelativeLayout) childView.findViewById(R.id.ly_select_problem);
        vh.textProblem = (TextView) childView.findViewById(R.id.text_problem);
        vh.editProblem = (EditText) childView.findViewById(R.id.edit_problem);
        vh.imgsList = (NoScrollGridView) childView.findViewById(R.id.images);
        vh.voiceRecord = (ImageView) childView.findViewById(R.id.voice_record);
        vh.addPhoto = (ImageView) childView.findViewById(R.id.add_photo);
        vh.flexBoxLayout = (FlexboxLayout) childView.findViewById(R.id.select_imgs_layout);

        vh.editPart.setVisibility(View.GONE);

        vh.housePartList.addAll(housePartList);
        vh.partsListView.setAdapter(new CommenAdapter<HousePart>(mContext, vh.housePartList, R.layout.layout_text_part) {
            @Override
            public void convert(ViewHolder helper, HousePart item, int position) {
                ((TextView) helper.getView(R.id.part_name)).setText(item.getText());
                ((TextView) helper.getView(R.id.part_name)).setBackgroundColor(item.isSelected() ? ContextCompat.getColor(mContext, R.color._7cb2ff) :
                        ContextCompat.getColor(mContext, R.color._f3f5f6));
                ((TextView) helper.getView(R.id.part_name)).setTextColor(item.isSelected() ? ContextCompat.getColor(mContext, R.color.white) :
                        ContextCompat.getColor(mContext, R.color._808080));

            }
        });
        vh.partsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                HousePart item = (HousePart) parent.getAdapter().getItem(position);
                vh.housePart = item;
                item.setSelected(true);
                for (int i = 0; i < vh.housePartList.size(); i++) {
                    if (i != position) {
                        vh.housePartList.get(i).setSelected(false);
                    }
                }
                ((CommenAdapter<HousePart>) parent.getAdapter()).notifyDataSetChanged();
                //重置数据
                vh.problemType = vh.housePart.getText();
                vh.problemName = null;
                vh.problemInfo = null;
                vh.problemOther = null;
                vh.textProblem.setText("");
                vh.editPart.setText("");
                vh.editProblem.setText("");
                if (position != parent.getAdapter().getCount() - 1) {
                    vh.editPart.setVisibility(View.GONE);
                    vh.lySelectProblem.setVisibility(View.VISIBLE);
                } else {
                    vh.editPart.setVisibility(View.VISIBLE);
                    vh.lySelectProblem.setVisibility(View.GONE);
                }
            }
        });
        vh.deleteProblem.setOnClickListener(onClickListener);
        vh.selectDirection.setOnClickListener(onClickListener);
        vh.lySelectProblem.setOnClickListener(onClickListener);
        vh.voiceRecord.setOnClickListener(onClickListener);
        vh.addPhoto.setOnClickListener(onClickListener);
        lsvh.add(vh);
        viewList.add(childView);
    }

    private void sortView() {
        if (viewList.size() > 1) {
            for (int i = 0; i < lsvh.size(); i++) {
                lsvh.get(i).hederLayout.setVisibility(View.VISIBLE);
                lsvh.get(i).problemIndex.setText(String.format("问题%d", i + 1));
            }
        } else {
            lsvh.get(0).hederLayout.setVisibility(View.GONE);
        }
    }


    private final int REQUEST_ONE = 0x1111;
    private final int REQUEST_TWO = 0x1112;
    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.delete_problem:
                    View view = (View) v.getParent().getParent().getParent().getParent();
                    for (int i = 0; i < lyAddItem.getChildCount(); i++) {
                        if (view.getId() == lsvh.get(i).id) {
                            lyAddItem.removeView(view);
                            lsvh.remove(i);
                            viewList.remove(i);
                            sortView();
                        }
                    }
                    break;
                case R.id.select_direction:
                    final View view2 = (View) v.getParent().getParent().getParent().getParent();
                    SelectDirectionWindow window = new SelectDirectionWindow(mContext);
                    window.showPopupWindow(lyAddItem);
                    window.setOnSelectDirection(new SelectDirectionWindow.OnSelectDirection() {
                        @Override
                        public void selectDirection(String direction) {
                            for (int i = 0; i < lyAddItem.getChildCount(); i++) {
                                if (view2.getId() == lsvh.get(i).id) {
                                    if (!TextUtils.isEmpty(direction))
                                        lsvh.get(i).selectDirection.setText(direction);
                                    lsvh.get(i).selectDirection.setBackgroundColor(ContextCompat.getColor(mContext, R.color._2692ff));
                                    lsvh.get(i).selectDirection.setTextColor(ContextCompat.getColor(mContext, R.color.white));
                                    lsvh.get(i).position = direction;
                                }
                            }
                        }
                    });
                    break;
                case R.id.ly_select_problem:
                    View view3 = (View) v.getParent().getParent().getParent();
                    for (int i = 0; i < lyAddItem.getChildCount(); i++) {
                        if (view3.getId() == lsvh.get(i).id) {
                            if (lsvh.get(i).housePart != null && lsvh.get(i).housePart.getId() != 0) {
                                Intent intent = new Intent(mContext, ProblemClassifyListActivity.class);
                                intent.putExtra("typeId", lsvh.get(i).housePart.getId());
                                intent.putExtra("vhIndex", i);//返回时需要是哪个vh的
                                startActivityForResult(intent, REQUEST_ONE);
                            }
                        }
                    }
                    break;
                case R.id.voice_record:
                    View view4 = (View) v.getParent().getParent().getParent().getParent();
                    for (int i = 0; i < lyAddItem.getChildCount(); i++) {
                        if (view4.getId() == lsvh.get(i).id) {
                            if (ContextCompat.checkSelfPermission(getApplicationContext(), RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                    ((CommitTaskActivity) mContext).requestPermissions(new String[]{RECORD_AUDIO},
                                            0);
                                }
                                return;
                            }
                            layoutRecorder.setVisibility(View.VISIBLE);
                            btnStop.setTag(i);
                            VoiceManager.getInstance(mContext).startVoiceRecord(AppConfig.DEFAULT_RECORD_SAVE_FILE_PATH + String.valueOf(taskDetail.getDetailId()) + File.pathSeparator);
                            voiceLineView.run();
                            recordTimer = new RecordTimer(99999999, 1000, timer);
                            recordTimer.start();
                            //vh 记录录音文件
                        }
                    }
                    break;
                case R.id.add_photo:
                    View view5 = (View) v.getParent().getParent().getParent().getParent();
                    int pos = 0;
                    for (int i = 0; i < lyAddItem.getChildCount(); i++) {
                        if (view5.getId() == lsvh.get(i).id) {
                            pos = i;
                            break;
                        }
                    }
                    Intent intent = new Intent(mContext, MultiImageSelectorActivity.class);
                    intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
                    intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 9);
                    intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
                    intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_POSITION, pos);
                    if (lsvh.get(pos).selectImgList != null && lsvh.get(pos).selectImgList.size() > 0) {
                        intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, lsvh.get(pos).selectImgList);
                    }
                    startActivityForResult(intent, REQUEST_TWO);
                    break;
                case R.id.img11:
                    int p = (int) v.getTag();//外层lsvh 的位置
                    View view6 = (View) v.getParent().getParent();
                    for (int i = 0; i < lsvh.get(p).flexBoxLayout.getChildCount(); i++) {
                        if (view6.getId() == imgHolderList.get(i).id) {
                            lsvh.get(p).flexBoxLayout.removeView(view6);
                            imgHolderList.remove(i);
                            lsvh.get(p).selectImgList.remove(i);
                        }
                    }
                    break;
                case R.id.delete_record:
                    int p1 = (int) v.getTag();//外层lsvh 的位置
                    int count = lsvh.get(p1).flexBoxLayout.getChildCount();
                    lsvh.get(p1).flexBoxLayout.removeViewAt(count - 1);
                    lsvh.get(p1).isHaveRecordView = false;
                    //清除该vh的录音文件记录,并删除文件
                    File file = new File(lsvh.get(p1).videoPath);
                    if (file.exists()) {
                        file.delete();
                    }
                    lsvh.get(p1).videoPath = "";
                    lsvh.get(p1).videoTime = 0;
                    break;
                case R.id.layout_play_record:
                    int p2 = (int) v.getTag();//外层lsvh 的位置
                    //播放录音文件
                    ViewsHolder vh = lsvh.get(p2);
                    try {
                        VoiceManager.getInstance(mContext).startPlay(vh.videoPath);
                    } catch (Exception e) {
                        return;
                    }
                    layoutRecorder.setVisibility(View.INVISIBLE);
                    layoutPlayRecorder.setVisibility(View.VISIBLE);
                    timerStart = new RecordTimer(999999999, 1000, timeStart);
                    timerStart.start();
                    String duration = "";
                    try {
                        duration = DateUtil.longToString(vh.videoTime * 1000, "mm:ss");
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    timeEnd.setText(duration);
                    btnStartPlay.setTag(p2);
                    btnStartPlay.setImageResource(R.mipmap.report_voice_stop);
                    break;

            }
        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_ONE:
                int vhIndex = data.getIntExtra("vhIndex", 0);//获取返回的viewholder
                //保存数据
                lsvh.get(vhIndex).problemName = data.getStringExtra("problemType");
                lsvh.get(vhIndex).problemInfo = data.getStringExtra("problem");
                lsvh.get(vhIndex).textProblem.setText(data.getStringExtra("problem"));
                break;
            case REQUEST_TWO:
                final int position = data.getIntExtra(MultiImageSelectorActivity.EXTRA_SELECT_POSITION, 0);
                lsvh.get(position).selectImgList.clear();
                lsvh.get(position).selectImgList.addAll(data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT));
                lsvh.get(position).flexBoxLayout.removeAllViews();
                for (int i = 0; i < lsvh.get(position).selectImgList.size(); i++) {
                    imgMark = i;
                    View view = layoutInflater.inflate(R.layout.grid_img_layout, null);
                    lsvh.get(position).flexBoxLayout.addView(view);
                    view.setId(imgMark);
                    getImgViewInstance(view, position);

                }
                if (!TextUtils.isEmpty(lsvh.get(position).videoPath)) {
                    View view = layoutInflater.inflate(R.layout.layout_record_item, null);
                    TextView recordTime = (TextView) view.findViewById(R.id.record_time);
                    recordTime.setText(new StringBuilder().append(lsvh.get(position).videoTime).append("\"").toString());
                    lsvh.get(position).flexBoxLayout.addView(view);
                    lsvh.get(position).isHaveRecordView = true;
                    ViewGroup.LayoutParams params = view.getLayoutParams();
                    if (params instanceof FlexboxLayout.LayoutParams) {
                        FlexboxLayout.LayoutParams layoutParams = (FlexboxLayout.LayoutParams) params;
                        layoutParams.setFlexGrow(0);
                        layoutParams.width = PixUtils.dip2px(mContext, 90);
                        layoutParams.setMaxWidth(PixUtils.dip2px(mContext, 90));
                        view.setLayoutParams(layoutParams);
                    }
                    ImageView imgView1 = (ImageView) view.findViewById(R.id.delete_record);
                    LinearLayout llPlay = (LinearLayout) view.findViewById(R.id.layout_play_record);
                    imgView1.setTag(position);
                    llPlay.setOnClickListener(onClickListener);
                    imgView1.setOnClickListener(onClickListener);
                }

                //adapter.notifyDataSetChanged();
                break;
        }
    }

    private void getImgViewInstance(View view, final int position) {
        final ImgHolder vh = new ImgHolder();
        vh.id = view.getId();//标识viewholder 存储唯一的childview 信息
        imgHolderList.add(vh);
        vh.mainImg = (ImageView) view.findViewById(R.id.img1);
        if (lsvh.get(position).selectImgList.get(vh.id) != null)
            Picasso.with(mContext)
                    .load(new File(ImageUtils.getCompressImagePath(lsvh.get(position).selectImgList.get(vh.id))))
                    .resize(300, 300)
                    .error(R.drawable.logo)
                    .into(vh.mainImg);
        vh.deleteImg = (ImageView) view.findViewById(R.id.img11);
        vh.deleteImg.setOnClickListener(onClickListener);
        vh.deleteImg.setTag(position);//记录外层viewholder的位置

    }

    private List<HousePart> housePartList = new ArrayList<>();

    private void getPartsList() {
        showLoadingDialog();
        ApiClient.getApiService().getPartsList(this, new TypeToken<ResultDO<List<HousePart>>>() {
        }.getType());
    }

    @Override
    public void onResponce(String key, Object result) {
        dissMissDialog();
        if (isFinish) {
            return;
        }
        switch (key) {
            case Api.PARTS_LIST:
                ResultDO<List<HousePart>> resultDO = (ResultDO<List<HousePart>>) result;
                if (resultDO.getCode() == 0) {
                    housePartList.clear();
                    housePartList.addAll(resultDO.getResult());
                    HousePart housePart = new HousePart();
                    housePart.setText("其他");
                    housePart.setId(0);
                    housePartList.add(housePart);
                    if (TextUtils.isEmpty(savedJson)) {
                        initView();
                    } else {
                        //读取草稿，恢复数据
                        Log.i("------CurrentTime", String.valueOf(System.currentTimeMillis()));
                        List<SaveReport> saveReportList = new ArrayList<>();
                        Gson gson = new Gson();
                        Type type = new TypeToken<List<SaveReport>>() {
                        }.getType();
                        saveReportList = gson.fromJson(savedJson, type);
                        Log.i("------CurrentTime", String.valueOf(System.currentTimeMillis()));
                        restoreViews(saveReportList);
                    }
                }
                break;
            case Api.CHANGE_TASK_STATUS:
                ResultDO resultDO1 = (ResultDO) result;
                if (resultDO1.getCode() == 0) {
                    finish();
                } else {
                    ToastUtils.showToast(mContext, resultDO1.getMessage());
                }
                break;
            case Api.UP_LOAD_MULTI_IMG:
                ResultDO<List<UploadImg>> resultDO2 = (ResultDO<List<UploadImg>>) result;
                if (resultDO2.getCode() == 0) {
                    List<UploadImg> filePaths = resultDO2.getResult();
                    for (int i = 0; i < filePaths.size(); i++) {
                        for (ViewsHolder vh : lsvh) {
                            if (vh.filePaths.containsKey(filePaths.get(i).getName())) {
                                vh.filePaths.put(filePaths.get(i).getName(), filePaths.get(i).getUrl());
                            }
                        }
                    }
                    getUploadJson();
                    submitReport();
                } else {
                    ToastUtils.showToast(mContext, resultDO2.getMessage());
                }
                break;
            case Api.SUBMIT_REPORT:
                ResultDO resultDO3 = (ResultDO) result;
                if (resultDO3.getCode() == 0) {
                    ToastUtils.showToast(mContext, "提交成功");
                    //删除草稿记录和录音文件
                    SharePerferenceUtils.getIns().removeKey(TASK_ID + taskDetail.getDetailId());
                    finish();
                } else {
                    ToastUtils.showToast(mContext, resultDO3.getMessage());
                }
                break;
        }
    }

    String json;

    private void getUploadJson() {
        List<UploadReport> datas = new ArrayList<>();
        for (int i = 0; i < lsvh.size(); i++) {
            ViewsHolder vh = lsvh.get(i);
            String video = null;
            List<String> imgs = new ArrayList<>();
            if (!TextUtils.isEmpty(vh.videoPath)) {
                video = vh.filePaths.remove(vh.videoPath.substring(vh.videoPath.lastIndexOf('/') + 1, vh.videoPath.length()));
            }
            Iterator iter = vh.filePaths.entrySet().iterator();
            while (iter.hasNext()) {
                String value = (String) ((Map.Entry) iter.next()).getValue();
                imgs.add(value);
            }

            UploadReport dat = new UploadReport(vh.floor, vh.position, vh.problemType, vh.problemName, vh.problemInfo,
                    vh.problemOther, video, vh.videoTime, StringUtils.listToString(imgs));
            datas.add(dat);
        }
        Gson gson = new Gson();
        json = gson.toJson(datas);
    }


    //提交报告
    private void submitReport() {
        ApiClient.getApiService().submitReport(taskDetail.getHouseId(), taskDetail.getDetailId(), json, this,
                new TypeToken<ResultDO>() {
                }.getType());
    }

    @Override
    public void onFailure() {
        dissMissDialog();
        ToastUtils.showToast(mContext, "网络连接错误");
    }

    public class ViewsHolder {

        private int id = -1;
        private RelativeLayout hederLayout;
        private TextView problemIndex;
        private ImageView deleteProblem;
        private EditText editFloor;
        private TextView selectDirection;
        private NoScrollGridView partsListView;
        private EditText editPart;
        private RelativeLayout lySelectProblem;
        private TextView textProblem;
        private EditText editProblem;
        private NoScrollGridView imgsList;
        private ImageView voiceRecord;
        private ImageView addPhoto;
        private FlexboxLayout flexBoxLayout;
        private boolean isHaveRecordView;


        private HousePart housePart;
        private List<HousePart> housePartList = new ArrayList<>();

        private ArrayList<String> selectImgList = new ArrayList<>();
        private String videoPath; //录音文件路径
        private HashMap<String, String> filePaths = new HashMap<>();//用于存放上传返回后的文件路径

        //保存的信息 用于提交报告
        private String floor; //楼层
        private String position; //方位
        private String problemType; //问题部件
        private String problemName; //问题名称
        private String problemInfo; //具体问题
        private String problemOther; //补充信息
        private String video;
        private long videoTime;//时长
        private String images;
    }

    private class UploadReport {
        //保存的信息 用于提交报告
        private String floor; //楼层
        private String position; //方位
        private String problemType; //问题部件
        private String problemName; //问题名称
        private String problemInfo; //具体问题
        private String problemOther; //补充信息
        private String video;
        private long videoTime;//时长
        private String images;

        private UploadReport(String floor, String position, String problemType, String problemName, String problemInfo,
                             String problemOther, String video, long videoTime, String images) {
            this.floor = floor;
            this.position = position;
            this.problemType = problemType;
            this.problemName = problemName;
            this.problemInfo = problemInfo;
            this.problemOther = problemOther;
            this.video = video;
            this.videoTime = videoTime;
            this.images = images;
        }
    }

    private class SaveReport {
        //保存的信息 用于保存草稿
        private String floor; //楼层
        private String position; //方位
        private String problemType; //问题部件
        private String problemName; //问题名称
        private String problemInfo; //具体问题
        private String problemOther; //补充信息
        private String video;//原始MP3文件路径
        private long videoTime;//时长
        private List<String> images;//原始图片路径

        private SaveReport(String floor, String position, String problemType, String problemName, String problemInfo,
                           String problemOther, String video, long videoTime, List<String> images) {
            this.floor = floor;
            this.position = position;
            this.problemType = problemType;
            this.problemName = problemName;
            this.problemInfo = problemInfo;
            this.problemOther = problemOther;
            this.video = video;
            this.videoTime = videoTime;
            this.images = images;
        }
    }


    private class ImgHolder {

        private int id = -1;
        private ImageView mainImg;
        private ImageView deleteImg;

    }


}
